﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;

namespace ScenarioFramework.WorkflowEngine
{
    public class EngineException : Exception 
    {
       public EngineException(string sMsgErr) :base(sMsgErr)
		{
		}
    }

    public class Engine
    {
        ScenarioFramework.WorkflowEngine.Scheduler.JobManager jobManager = null;
        private static ILog logger = LogManager.GetLogger(typeof(Engine));

        public ScenarioFramework.WorkflowEngine.Scheduler.JobManager Scheduler
        {
            get { return jobManager; }
        }

        public void StartUp(Boolean bStartScheduler)
        {
            logger.Info("Starting Process Engine");
            WAPI.Response wapiResponse = new WAPI.Response();
            WAPI.Session.InitSession(ref wapiResponse, "Engine", 7);

            if (wapiResponse.iCode != 0)
                throw new EngineException(wapiResponse.sMsg);

            if (bStartScheduler)
            {
                logger.Info("Scheduler");
                jobManager = new ScenarioFramework.WorkflowEngine.Scheduler.JobManager();
                jobManager.StartListener();
            }
        }

        public void StartUp()
        {
            StartUp(true);
        }

        public void ShutDown()
        {
            if (jobManager != null)
            {
                logger.Info("Stopping Scheduler");
                jobManager.Stop();
            }

            logger.Info("Stopping Process Engine");
            WAPI.Response wapiResponse = new WAPI.Response();
            WAPI.Session.EndSession(ref wapiResponse);

            if (wapiResponse.iCode != 0)
                throw new EngineException(wapiResponse.sMsg);
        }

        public void StartProcess(string sProcess)
        {
            long lProcessId = 0;
            WAPI.Response wapiResponse = new ScenarioFramework.WAPI.Response();
            WAPI.Process.CreateProcessInstance(sProcess, ref lProcessId, ref wapiResponse);

            if (wapiResponse.iCode != 0)
                throw new EngineException(wapiResponse.sMsg);

            WAPI.Process.StartProcessInstance(lProcessId, ref wapiResponse);
            if (wapiResponse.iCode != 0)
                throw new EngineException(wapiResponse.sMsg);
        }


    }
}
